//join.js
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var uid = 0;
var token = '';
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
});
var wxAuthFail = true;

Page({
  data: {
    util: util,
    tc: 0,
    uid: 0, //当前登录用户Id
    token: '', //post请求时，当前登录用户token
    authData: {}, //未认证
    cataType: '',

    colorSet: '',

    chooseAddr: '',

    shopInfo: '',

    org_info: '',
    tel: '',
    phone: '',

    showAuthView: false,
    authToastData: '',

    iden_zheng: '',
    iden_bei: '',

    yyzz_img: '',
    uploadImg:[],

  },

  uploadParams: '',

  iden_zheng_url: '',
  iden_bei_url: '',
  yyzz_img_url: '',

  wxAuthFail: true,
  inviteuid: '',


  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },

  onLoad: function(options) {
    var that = this;
    var title = options.title;
    
    title = decodeURI(title);
    wx.setNavigationBarTitle({
      title: title ? title : '提交申请资料',
    })
    var tc = app.get_tc();

    // 10: 咨客  11:优惠券核销员  20: 经销商  30: 供货商   40:会员   50:医生  60: 美容师
    // 8：老板   80：采购员  81:管理员   9: 一级分销商  90: 二级分销商 
    this.setData({
      tc: tc,
      sex: tc == 1 ? ["請選擇性別", "男", "女"] : ["请选择性别", "男", "女"],
      cataType: options.type
    });

    this.inviteuid = options.inviteuid ? options.inviteuid : '';
 
    this.showAuthView(false, true);

    // //获取绑定orgid信息
    // app.getOrgInfo(function(res) {
    //   var tel_num = res.bindOrgInfo.has_app ? res.bindOrgInfo.has_app : res.dataOrgInfo.has_app;
    //   var phone_num = res.bindOrgInfo.phone ? res.bindOrgInfo.phone : res.dataOrgInfo.phone;
    //   that.setData({
    //     org_info: res,
    //     tel: tel_num ? tel_num : '',
    //     phone: phone_num ? phone_num : ''
    //   })
    // });

    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定机构信息：", res)
      that.setData({
        org_info: res,
      })

      
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
  },
  //设置titlebar 样式
  resetNavColor: function() {
    var bg_color = '#f0f0f0';
    var fg_color = '#000000';
    if (this.data.colorSet) {
      bg_color = this.data.colorSet.titlebg;
      fg_color = this.data.colorSet.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },


  //获取用户认证状态
  getAuth: function(uid, token) {
    var that = this;

    var privatekey = utilMd5.hexMD5(uid + 'getUserAuth' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getUserAuth",
        uid: uid,
        catatype: that.data.cataType,
        privatekey: privatekey
      },
      method: 'GET',
      success: function(responseData) {
        var data = responseData.data;
        console.log("已提交的认证信息：", data);
        if (data && data.res != false && data.realname) {
          //更新数据
          var iden_z = {};
          iden_z.path = data.photo;
          var iden_b = {};
          iden_b.path = data.photo2;
          var yyzz_p = {};
          yyzz_p.path = data.zhizhao;

          //所在地信息
          var addrPoint = {};
          addrPoint.address = data.address;
          addrPoint.latitude = data.lat; //纬度
          addrPoint.longitude = data.lon; //经度
          //读取门店信息
          if(data.shopid){
            app.GetUserInfo(data.shopid, function (res) {
              res.username = res.uname;
              that.setData({
                shopInfo: res
              });
            });
          }
          var mendianImg = [];
          mendianImg = mendianImg.concat(data.mendian_photos);
          that.setData({
            authData: data,
            uploadImg: mendianImg,
            chooseAddr: addrPoint,
            iden_zheng: iden_z,
            iden_bei: iden_b,
            yyzz_img: yyzz_p
          });
        } else {
          that.setData({
            authData: null
          });
        }
      }
    });
  },

  //上传认证图片 
  uploadImgs: function(imgInfo, uploadType) {
    wx.showLoading({
      title: 'loading...',
      mask: "true"
    })
    var that = this;

    var imageSrc = imgInfo.path;
    var nowd = new Date();
    var upy_imgPath = util.formatTime(nowd, "", "");
    var imgName = upy_imgPath + "_" + this.data.uid + '_' + imageSrc.split('_')[1];
    var imgUrl = '/renzheng_img/' + imgName;

    upyun.upload({
      localPath: imageSrc,
      remotePath: imgUrl,
      success: function(res) {
        var resImgInfo = JSON.parse(res.data);
        // iden_zheng_url: '',
        //   iden_bei_url: '',
        //     yyzz_img_url: '',
        if (uploadType == 'zheng') {
          that.iden_zheng_url = util.upyun_imgHost + resImgInfo.url;
        } else if (uploadType == 'bei') {
          that.iden_bei_url = util.upyun_imgHost + resImgInfo.url;
        } else if (uploadType == 'ying') {
          that.yyzz_img_url = util.upyun_imgHost + resImgInfo.url;
          console.log("营业执照图片链接：" + that.yyzz_img_url);
        }
        if ((that.data.cataType == 30 || that.data.cataType == 50 || that.data.cataType == 11) && that.data.yyzz_img && that.yyzz_img_url) {
          that.uploadParams.photo = '';
          that.uploadParams.photo2 = '';
          that.uploadParams.zhizhao = that.yyzz_img_url;
          that.commitData();
        } else if (that.iden_zheng_url && that.iden_bei_url && (!that.data.yyzz_img || (that.data.yyzz_img && that.yyzz_img_url))) {
          that.uploadParams.photo = that.iden_zheng_url;
          that.uploadParams.photo2 = that.iden_bei_url;
          that.uploadParams.zhizhao = that.yyzz_img_url;
          that.commitData();
        }
      },

      fail: function({
        errMsg
      }) {
        wx.showModal({
          title: '提示',
          content: '提交失败，请稍后重试',
        })
        wx.hideLoading();
      }
    })

  },

  //填写资料提交
  joinSubmit: function(e) {
    var that = this;
    var uid = e.detail.value.uid;
    var realName = e.detail.value.name;
    var token = e.detail.value.token;
    var mobile = e.detail.value.mobile;

    var mendian_mobile = e.detail.value.mendian_mobile;
    var mendian_name = e.detail.value.mendian_name;
    var mendian_addr = e.detail.value.mendian_addr;


    var lat = '';
    var lon = '';
    var address = '';
    var shopid = '';
    var message = e.detail.value.msg ? e.detail.value.msg : '';
    var privatekey = utilMd5.hexMD5(uid + 'userauth' + token);
    if (!realName) {
      app.dialog('请填写姓名', 'loading');
      return;
    }
    if (!mobile) {
      app.dialog('请填写手机号码', 'loading');
      return;
    }

    if (that.data.cataType == 11 || that.data.cataType == 60) {
      if (!that.data.shopInfo) {
        app.dialog('请选择所属门店', 'loading');
        return;
      }
      shopid = that.data.shopInfo.uid;
    } else if (that.data.cataType == 30 ||that.data.cataType == 20) {
      if (!that.data.chooseAddr || !that.data.chooseAddr.address) {
        app.dialog('请选择所在地', 'loading');
        return;
      }
      lat = that.data.chooseAddr.latitude;
      lon = that.data.chooseAddr.longitude;
      address = that.data.chooseAddr.address;
    }

    if (util.orgid != 17784 && (that.data.cataType == 30 || that.data.cataType == 9 || that.data.cataType == 90)) {
      if (!that.data.iden_zheng || !that.data.iden_zheng.path || !that.data.iden_bei || !that.data.iden_bei.path) {
        app.dialog('请选择身份证', 'loading');
        return;
      }
    }
    if (that.data.cataType == 30 || that.data.cataType == 50 || that.data.cataType == 11) {
      if (!that.data.yyzz_img) {
        app.dialog('请上传证明资料', 'loading');
        return;
      }
    }

    if (!mendian_name) {
      app.dialog('请填写门店用户名', 'loading');
      return;
    }

    var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }

    that.uploadParams = {
      publickey: util.publiccode,
      ac: "userauth",
      uid: uid,
      firstfxs: this.inviteuid,
      realname: realName,
      phone: mobile,
      catatype: that.data.cataType,
      address: address,
      shopid: shopid,
      lat: lat, //纬度
      lon: lon, //经度
      message: message,
      privatekey: privatekey,
      mendian_photos: that.data.uploadImg.map(function (item) { return item.replace('wxfile://tmp_', 'https://img.maxdoge.com/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(','),
      mendian_mobile:mendian_mobile,
      mendian_name:mendian_name,
      mendian_addr:mendian_addr
    };

    if (that.data.cataType == 30 || that.data.cataType == 9 || that.data.cataType == 90 || that.data.cataType == 50 || that.data.cataType == 11) {
      if (util.orgid != 17784 && (that.data.cataType == 30 || that.data.cataType == 9 || that.data.cataType == 90)) {
        if (that.data.iden_zheng.path.indexOf(util.upyun_imgHost) == 0) {
          that.iden_zheng_url = that.data.iden_zheng.path;
          that.uploadParams.photo = that.data.iden_zheng.path;
        } else {
          that.uploadImgs(that.data.iden_zheng, 'zheng');
        }

        if (that.data.iden_bei.path.indexOf(util.upyun_imgHost) == 0) {
          that.iden_bei_url = that.data.iden_bei.path;
          that.uploadParams.photo2 = that.data.iden_bei.path;
        } else {
          that.uploadImgs(that.data.iden_bei, 'bei');
        }
      }

      // that.uploadParams.zhizhao = that.yyzz_img_url;
      if (that.data.yyzz_img && that.data.yyzz_img.path.indexOf(util.upyun_imgHost) == 0) {
        that.yyzz_img_url = that.data.yyzz_img.path;
        that.uploadParams.zhizhao = that.data.yyzz_img.path;
        console.log("已上传----营业执照图片链接：" + that.yyzz_img_url);
      } else if (that.data.yyzz_img) {
        console.log("去上传---营业执照图片链接：" + that.data.yyzz_img);
        that.uploadImgs(that.data.yyzz_img, 'ying');
      }

      if (((that.data.cataType == 9 || that.data.cataType == 90) && that.iden_zheng_url && that.iden_bei_url) && (!that.data.yyzz_img || (that.data.yyzz_img && that.yyzz_img_url))) {
        wx.showLoading({
          title: 'loading...',
          mask: 'true'
        })
        that.commitData();
      } else if ((that.data.cataType == 50 || that.data.cataType == 11) && that.data.yyzz_img && that.yyzz_img_url){
        wx.showLoading({
          title: 'loading...',
          mask: 'true'
        })
        that.commitData();
      }
    } else {
      wx.showLoading({
        title: 'loading...',
        mask: 'true'
      })
      that.commitData();
    }
  },

  commitData: function() {

    var that = this;
    util.api({
      data: that.uploadParams,
      method: 'POST',
      success: function(responseData) {
        wx.hideLoading();
        var data = responseData.data;
        console.log('提交认证信息返回：', data);
        if (data.res === true) {
          wx.showModal({
            title: '提示',
            content: '资料已提交',
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })

        } else if (data.msg.indexOf('already') >= 0) {
          wx.showModal({
            title: '提示',
            content: '您已提交过申请资料',
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '提交失败，请稍后重试',
            showCancel: false,
          })
        }
      }
    });

  },

  //获取会员介绍 和 特权 文字
  getHuiyuanNotice: function() {
    var that = this;
    var privatekey = utilMd5.hexMD5(uid + 'getUserAuth' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "groupcontent"
      },
      method: 'GET',
      success: function(responseData) {

      }
    });
  },

  selectShop: function() {
    var path = "/pages/use_yhq/use_yhq?selshop=true"
    wx.navigateTo({
      url: path,
    })
  },
  setSelectShop: function(shop_info) {
    this.setData({
      shopInfo: shop_info
    })
  },

  selectAddress: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log("选择地址：", res);
        that.setData({
          chooseAddr: res
        })
      },
    })
  },

  makeCallPhone: function(e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function(e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function(e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },


  userCancelAuth: function() { //用户取消授权
    this.hiddenAuthView();
    wx.navigateBack({
      delta: 1
    })
  },
  showAuthView: function(showCancel, reAuth) {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log("已授权列表：", res);
        var authStatus_userInfo = res.authSetting["scope.userInfo"];
        if (authStatus_userInfo) {
          that.getLoginUserInfo();
        } else if (app.getShowAuthViewSign() || reAuth) {
          var authToastOb = {};
          authToastOb.showCancel = showCancel;
          authToastOb.msg = app.getBindOrgName() + " 需要您的授权"
          that.setData({
            showAuthView: true,
            authToastData: authToastOb
          })
        }
      }
    });
  },
  hiddenAuthView: function() {
    this.setData({
      showAuthView: false
    })
  },
  loginUserInfo: function(res) {
    if (res.detail.encryptedData) { //如果包含有这个字段，说明用户授权了
      this.getLoginUserInfo();
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },

  getLoginUserInfo: function() {
    var that = this;
    //读取登录用户信息
    app.LoginUserInfo(function(res) {
      if (res && res != -1) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
        })
        uid = res.uid;
        token = res.token;
        //获取认证状态
        that.getAuth(uid, token);
      }

    }, that.inviteuid);
  },


  //选择图片
  selectLocalImg: function(res) {
    //选择类型  iden_z: 身份证正面 iden_b: 身份证背面   yyzz：营业执照
    var sel_type = res.currentTarget.dataset.seltype;
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;

        var imgInfo = {};
        imgInfo.path = tempFilePaths[0];
        if (sel_type == 'iden_z') { //身份证正面
          that.setData({
            iden_zheng: imgInfo
          })
        } else if (sel_type == 'iden_b') { //身份证背面
          that.setData({
            iden_bei: imgInfo
          })
        } else if (sel_type == 'yyzz') { //营业执照
          that.setData({
            yyzz_img: imgInfo
          })
        }
      },

      fail: function({
        errMsg
      }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },

  uploadImgt: function () {
    var that = this;
    var photos = this.data.uploadImg;
    if (photos.length > 1) {
      app.dialog('只能传一张二维码', 'loading');
      return false;
    }

    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFilePaths = res.tempFilePaths;
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              // jobj.put("url", recordUrl);
              // jobj.put("name", imgFileName);
              // jobj.put("type", resJob.optString("mimetype"));
              // jobj.put("size", resJob.optInt("file_size"));
              // jobj.put("hash", resJob.optString("sign"));
              // jobj.put("extension", resJob.optString("image-type"));
              // jobj.put("save_path", savePath);
              // jobj.put("save_name", savename);
              // jobj.put("width", resJob.optInt("image-width"));
              // jobj.put("height", resJob.optInt("image-height"));
            },
            fail: function ({ errMsg }) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  //删除图片
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  },



 

})